package me.aip.mov.minio;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author aa
 * @description
 *
 *配置格式
 * minio:
 *   conf:
 *     enable: true
 *     url: http://140.143.135.112:9100/
 *     accesskey:  minio
 *     secretkey: Minio12345
 *     bucket: dev
 *
 *
 *
 */

@ConditionalOnProperty(name = "minio.conf.enable")
@Configuration
public class MinIoService {

    private final static Logger logger = LoggerFactory.getLogger(MinIoConfig.class);

    @Resource
    private MinIoConfig minIoConfig;

    @Bean
    public MinioClient getClient(){

        MinioClient minioClient = MinioClient.builder()
                .endpoint(minIoConfig.getUrl())
                .credentials(minIoConfig.getAccesskey(), minIoConfig.getSecretkey())
                .build();
        try{
            //桶检查与创建
            checkBucket(minioClient, minIoConfig.getBucket());
            checkBucket(minioClient, minIoConfig.getBucketPublic());

        }catch (Exception e){
            throw new RuntimeException("create  bucket "+ minIoConfig.getBucketPublic() +" error : {}", e);
        }
        return minioClient;
    }

    private void checkBucket(MinioClient minioClient, String bucket) throws Exception{
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
                throw new RuntimeException("create  bucket [{}] failure");
            } else {
                logger.info("minio bucket [{}] create successful", bucket);
            }
        } else {
            logger.info("minio bucket [{}] exists", bucket);
        }
    }

    @ConditionalOnBean(MinioClient.class)
    @Bean
    @Resource
    public MinIoUtil getMinIoBean(MinioClient minioClient,MinIoConfig minIoConfig){
        return  new MinIoUtil(minioClient,minIoConfig);
    }


}
